#!/usr/bin/python3
# -*- coding: utf-8 -*-

from __future__ import print_function

import tkinter
from tkinter import ttk
import tkinter.messagebox
from tkinter import *
import tkinter.filedialog
import PIL
from PIL import ImageTk
from PIL import Image

import win32con, win32api
import subprocess
import os
import time
from datetime import datetime
import binascii
import sys
import json
import threading
import ctypes
import platform
import random
#import keyboard

BASE_DIR = "C:\\Users\\Public\\Documents\\eat_what\\"
CONFIG_FILE_PATH = "C:\\Users\\Public\\Documents\\eat_what\\config.json"

'''
period: xx: d-日，w-周,m-月,y-年,m-早上,n-中午,e-晚上,例如wn是以周中午循环,''为依次菜单所有循环
'''

menu_config = { 'period':'wn',\
                'menu':['浆面条手抓饼','老碗面','凉皮饼夹菜','热干面饼夹菜',' ', '浆面条饼夹菜',' ',' ',' '],\
                }
select_thread = None
space_pressed = False
button3_xy = [0,0]

def run_prg(cmd):
    cmd_result = subprocess.Popen(cmd,
                                  shell = True,
                                  stderr = subprocess.STDOUT,
                                  stdin = subprocess.PIPE,
                                  stdout = subprocess.PIPE).communicate()[0]
    return cmd_result

def set_win_center(root, curWidth='', curHight=''):
    '''
    设置窗口大小，并居中显示
    :param root:主窗体实例
    :param curWidth:窗口宽度，非必填，默认200
    :param curHight:窗口高度，非必填，默认200
    :return:无
    '''
    if not curWidth:
        '''获取窗口宽度，默认200'''
        curWidth = root.winfo_width()
    if not curHight:
        '''获取窗口高度，默认200'''
        curHight = root.winfo_height()
    # print(curWidth, curHight)

    # 获取屏幕宽度和高度
    scn_w, scn_h = root.maxsize()
    # print(scn_w, scn_h)

    # 计算中心坐标
    cen_x = (scn_w - curWidth) / 2
    cen_y = (scn_h - curHight) / 3
    # print(cen_x, cen_y)

    # 设置窗口初始大小和位置
    size_xy = '%dx%d+%d+%d' % (curWidth, curHight, cen_x, cen_y)
    root.geometry(size_xy)

#画圆角矩形
def round_rectangle(canvas,x1, y1, x2, y2, radius=25, **kwargs):
    points = [x1+radius, y1,
              x1+radius, y1,
              x2-radius, y1,
              x2-radius, y1,
              x2, y1,
              x2, y1+radius,
              x2, y1+radius,
              x2, y2-radius,
              x2, y2-radius,
              x2, y2,
              x2-radius, y2,
              x2-radius, y2,
              x1+radius, y2,
              x1+radius, y2,
              x1, y2,
              x1, y2-radius,
              x1, y2-radius,
              x1, y1+radius,
              x1, y1+radius,
              x1, y1]

    return canvas.create_polygon(points, **kwargs, smooth=True)

def modify_menu(args=None,cv=None,ct=None):
    if args == None:
        return
    #print(args)
    xy = [[200,200],[400,200],[600,200],[200,400],[400,400],[600,400],[200,600],[400,600],[600,600]]
    index = 4
    for _xy in xy:
        if args[0] < _xy[0] and args[1] < _xy[1]:
            index = xy.index(_xy)
            break
    if index != 4:
        win = tkinter.Toplevel()
        win.title("修改菜单")  #窗口名
        win.geometry('200x25+{}+{}'.format(args[2],args[3])) #640 480为窗口大小，+200 +100 定义窗口弹出时的默认展示位置
        win.resizable(False,False)
        menu_entry = tkinter.Entry(win,width=30) #初始化 ,font=('microsoft yahei', 20, 'bold')
        menu_entry.grid(row=0,column=1)
        if index < len(menu_config['menu']):
            menu_entry.insert(0,menu_config['menu'][index])
        win_pram = {"name":"win_modify",\
                "win":win,\
                "index":index,\
                "menu_entry":menu_entry,\
                "cv":cv,\
                "ct":ct,\
        }
        win.protocol("WM_DELETE_WINDOW", (lambda : win_closing(win_pram)))

    return

def win_closing(pram=None):
    if pram == None:
        return
    if pram['name'] == 'win_main':
        if select_thread != None:
            _async_raise(select_thread, SystemExit)
        pram['win'].destroy()
    if pram['name'] == 'win_modify':
        menu = pram['menu_entry'].get()
        index = pram['index']
        if index < len(menu_config['menu']):
            menu_config['menu'][index] = menu
            pram['cv'].itemconfig(pram['ct'][index],text=menu)
        else:
            menu_config['menu'].append(menu)
        with open(CONFIG_FILE_PATH, 'w') as f:
            f.write(json.dumps(menu_config))
        pram['win'].destroy()
    return

def select_task(pram=None,args=None):
    global space_pressed
    if pram == None:
        return
    clr = ['pink','cyan','lime','gold','peru','plum','coral','skyblue','orange']
    index_prev = 0
    canvas = pram['canvas']
    rect = pram['rect']
    space_isp = False
    while True:
        time.sleep(0.1)
        #if keyboard.is_pressed('space'):
        #    while keyboard.is_pressed('space'):
        if space_pressed:
            space_isp = not space_isp
            space_pressed = False
        if not space_isp:
            index = random.randint(0,8)
            canvas.itemconfig(rect[index_prev],fill=clr[index_prev])
            if index == 4:
                continue
            canvas.itemconfig(rect[index],fill='red')
            index_prev = index
    return

def creat_win(main=False,pram=None,titlep=''):
    win = None
    if main:
        win = tkinter.Tk()
    else:
        win = tkinter.Toplevel()
    title = "吃啥呢???"+titlep
    win.title(title)  #窗口名
    #win.geometry('980x600+10+10') #640 480为窗口大小，+200 +100 定义窗口弹出时的默认展示位置
    set_win_center(win,600,600)
    win.resizable(False,False)
    if os.path.exists('logo.png'):
        win.iconphoto(False,tkinter.PhotoImage(file='logo.png'))

    canvas = tkinter.Canvas(win, width=600, height=600, background='white')
    canvas.pack()

    clr = ['pink','cyan','lime','gold','peru','plum','coral','skyblue','orange']
    rect=[]
    for i in range(0,3):
        for j in range(0,3):
            x1 = i*200
            y1 = j*200
            x2 = x1+200
            y2 = y1+200
            rect.append(round_rectangle(canvas,x1,y1,x2,y2,outline='',fill=clr[i*3+j]))
    canvas.create_text(300,280,text="吃啥呢",font=('microsoft yahei', 20, 'bold'),fill='white')
    canvas.create_text(300,320,text="按下空格就知道",font=('microsoft yahei', 20, 'bold'),fill='white')

    index = 0
    clr = ['orange','pink','cyan','lime','gold','peru','plum','coral','skyblue']
    xy = [[100,100],[300,100],[500,100],[100,300],[300,300],[500,300],[100,500],[300,500],[500,500]]
    ct = []
    for m in menu_config['menu']:
        ct.append(canvas.create_text(xy[index][0],xy[index][1],text=menu_config['menu'][index],font=('microsoft yahei', 20, 'bold'),fill=clr[index]))
        index = index + 1
        if index == 4:
            continue
        if index > 8:
            break

    global button3_xy
    menubar = tkinter.Menu(win,tearoff=False)
    menubar.add_command(label="修改菜单",command=lambda:modify_menu(button3_xy,canvas,ct))
    def xShowMenu(event):
        global button3_xy
        button3_xy = [event.x, event.y]+[event.x_root, event.y_root]
        menubar.post(event.x_root, event.y_root)   # #将菜单条绑定上事件，坐标为x和y的root位置
    win.bind("<Button-3>", xShowMenu)#绑定右键事件
    def xKey(event):
        global space_pressed
        if event.keysym == "space":
            space_pressed = True
    #win.bind("<Key>", xKey)#绑定所有键事件
    win.bind("<KeyPress-space>", xKey)#绑定空格按键键事件

    win_pram = {"name":"win_main",\
                "win":win,\
                "rect":rect,\
                "canvas":canvas,\
    }

    select_thread = threading.Thread(target=select_task,args=(win_pram,None))
    select_thread.setDaemon(True)
    select_thread.start()

    win.protocol("WM_DELETE_WINDOW", (lambda : win_closing(win_pram)))
    win.mainloop()
    return

def main():
    global menu_config
    if not os.path.exists(BASE_DIR):
        os.makedirs(BASE_DIR)
        win32api.SetFileAttributes(BASE_DIR, win32con.FILE_ATTRIBUTE_HIDDEN)
    if not os.path.exists(CONFIG_FILE_PATH):
        with open(CONFIG_FILE_PATH, 'w') as f:
            f.write(json.dumps(menu_config))
    else:
        try:
            with open(CONFIG_FILE_PATH, 'r') as f:
                menu_config = json.loads(f.read())
        except:
            with open(CONFIG_FILE_PATH, 'w') as f:
                f.write(json.dumps(menu_config))

    creat_win(True,titlep=' v1.0 @build 20230418')


if __name__ == '__main__':
    main()
    exit()
